//
//  WDNativeViewController.m
//  WDPolymerizeSDK
//
//  Created by little People on 2023/5/31.
//

#import "WDNativeViewController.h"
#import "WDNSLog.h"
#import "WDNativeModel.h"
#import "WDSourceManager.h"
#import "WDSourceManager.h"
#import "WDNariveAdView.h"
#import "WDBMSModel.h"
#import "WDCardModel.h"
#import "WDCardZDYManager.h"
#import "WDCallBackManager.h"
#import "WDAdStatusManager.h"
#import "WDOrientationManager.h"
@interface WDNativeViewController ()<GADVideoControllerDelegate,GADNativeAdDelegate>
@property (nonatomic, strong)WDNariveAdView *adContentView;
/// The native ad view that is being presented.
@property(nonatomic, strong) GADNativeAdView *nativeAdView;

@property (nonatomic, copy)NSString *deepLink;
@end

@implementation WDNativeViewController

- (void)viewWillTransitionToSize:(CGSize)size withTransitionCoordinator:(id <UIViewControllerTransitionCoordinator>)coordinator
{
    BOOL isPortraitScreen = NO;
    if (@available(iOS 16.0, *)) {
        // iOS16 需要使用 UIWindowScene 来区分横竖屏
        NSArray *array = [[[UIApplication sharedApplication] connectedScenes] allObjects];
        UIWindowScene *scene = [array firstObject];
        isPortraitScreen = scene.interfaceOrientation == UIDeviceOrientationPortrait;
    } else {
        // 这里是 UIDeviceOrientationLandscapeLeft（我们需要 Home 按键在右边）
        // UIDeviceOrientationLandscapeLeft,       // Device oriented horizontally, home button on the right
        isPortraitScreen = [UIDevice currentDevice].orientation == UIDeviceOrientationPortrait;
    }
    if (isPortraitScreen)
    {
        if (self.isCardAd)
        {
            if (self.isJsonSource) {
                [self customCardNativeAd];
            }else{
                [self cardNativeAd];
            }
            
        }
        else
        {
            [self normalNativeAd];
        }
    }
}


- (void)orientationDidChange:(NSNotification *)note
{
//    WDLog(@"NSNotification:%@, orientation:%d", note.userInfo, [(UIDevice *)note.object orientation]);
    if ([(UIDevice *)note.object orientation] == UIDeviceOrientationPortrait)
    {
        if (self.isCardAd)
        {
            if (self.isJsonSource) {
                [self customCardNativeAd];
            }else{
                [self cardNativeAd];
            }
            
        }
        else
        {
            [self normalNativeAd];
        }
    }
}

-(void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    
    UIInterfaceOrientation dori = [UIApplication sharedApplication].statusBarOrientation;
    if (dori == UIInterfaceOrientationPortrait){
        if (self.isCardAd)
        {
            if (self.isJsonSource) {
                [self customCardNativeAd];
            }else{
                [self cardNativeAd];
            }
            
        }
        else
        {
            [self normalNativeAd];
        }
    }else{
        [[NSUserDefaults standardUserDefaults] setObject:@"1" forKey:@"WDOrientation"];
        [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(orientationDidChange:) name:UIDeviceOrientationDidChangeNotification object:nil];
        if (@available(iOS 16.0, *)) {
            // setNeedsUpdateOfSupportedInterfaceOrientations 方法是 UIViewController 的方法
            [self setNeedsUpdateOfSupportedInterfaceOrientations];
            NSArray *array = [[[UIApplication sharedApplication] connectedScenes] allObjects];
            UIWindowScene *scene = [array firstObject];
            // 屏幕方向
            UIInterfaceOrientationMask orientation = UIInterfaceOrientationMaskPortrait;
            UIWindowSceneGeometryPreferencesIOS *geometryPreferencesIOS = [[UIWindowSceneGeometryPreferencesIOS alloc] initWithInterfaceOrientations:orientation];
            // 开始切换
            [scene requestGeometryUpdateWithPreferences:geometryPreferencesIOS errorHandler:^(NSError * _Nonnull error) {
                WDLog(@"错误:%@", error);
            }];
        }
        else{
    //        [self interfaceOrientation:UIInterfaceOrientationPortrait];
            NSNumber *orientationTarget = [NSNumber numberWithInteger:UIInterfaceOrientationPortrait];
            [[UIDevice currentDevice] setValue:orientationTarget forKey:@"orientation"];
        }
    }
    [[WDAdStatusManager shareStatusManager] adCompletedWithEventName:NATIVE_EVENT_NAME];
}

- (void)interfaceOrientation:(UIInterfaceOrientation)orientation
{
  if ([[UIDevice currentDevice] respondsToSelector:@selector(setOrientation:)]) {
    SEL selector = NSSelectorFromString(@"setOrientation:");
    NSInvocation *invocation = [NSInvocation invocationWithMethodSignature:[UIDevice instanceMethodSignatureForSelector:selector]];
    [invocation setSelector:selector];
    [invocation setTarget:[UIDevice currentDevice]];
//    int val = orientation;
    // 从2开始是因为0 1 两个参数已经被selector和target占用
    [invocation setArgument:&orientation atIndex:2];
    [invocation invoke];
  }
}

/**
 Description  刷新设备方向
 */
- (void)refreshRotationToDeviceOrientation
{
     [UIViewController attemptRotationToDeviceOrientation];
}

- (UIInterfaceOrientationMask)supportedInterfaceOrientations
{
    return UIInterfaceOrientationMaskPortrait;
}
- (UIInterfaceOrientation)preferredInterfaceOrientationForPresentation
{
    return UIInterfaceOrientationPortrait;
}



- (void)viewDidLoad {
    [super viewDidLoad];
//    [[NSNotificationCenter defaultCenter] addObserverForName:UIDeviceOrientationDidChangeNotification object:nil queue:nil usingBlock:^(NSNotification * _Nonnull note) {
////        WDLog(@"NSNotification:%@, orientation:%d", note.userInfo, [(UIDevice *)note.object orientation]);
//
//
//    }];
//
    
    
//    if (self.isCardAd)
//    {
//        if (self.isJsonSource) {
//            [self customCardNativeAd];
//        }else{
//            [self cardNativeAd];
//        }
//
//    }
//    else
//    {
//        [self normalNativeAd];
//    }
    // Do any additional setup after loading the view.
}

- (void)customCardNativeAd
{
    self.view.backgroundColor = [UIColor clearColor];
    CGFloat safeAreaTop = 0.0;
    CGFloat safeAreaBottom = 0.0;
    if (@available(iOS 11.0, *)) {
        UIViewController *rootViewController = [[[UIApplication sharedApplication].windows objectAtIndex:0] rootViewController];
        safeAreaTop = rootViewController.view.safeAreaInsets.top;
        safeAreaBottom = rootViewController.view.safeAreaInsets.bottom;
    }
    UIView *bv = [[UIView alloc] initWithFrame:CGRectMake(10, self.view.frame.size.height-350-safeAreaBottom-10, 250, 350)];
    bv.backgroundColor = [UIColor whiteColor];
//    bv.layer.cornerRadius = 8;
    [self.view addSubview:bv];
    
    WDCustomCardModel *model = [[WDCardZDYManager shareCardZDYManager] getCustomCardModel];
    self.deepLink = model.deepLink;
    WDLog(@"WDCustomCardModel====%@",model.appName);
    WDLog(@"WDCustomCardModel====%@",model.bannerUrl);

    UIImageView *mediaImageView = [[UIImageView alloc] initWithFrame:CGRectMake(5, bv.frame.size.height/2-70, bv.frame.size.width-10, 140)];
    mediaImageView.image = model.bannerImage;
//    mediaImageView.center = bv.center;
    [bv addSubview:mediaImageView];
    

    
    UILabel *nameLabel = [[UILabel alloc] initWithFrame:CGRectMake(0, bv.frame.size.height-40, bv.frame.size.width-60, 40)];
    nameLabel.text = model.appName;
    [nameLabel setFont:[UIFont fontWithName:@"Helvetica-Bold" size:20]];
    nameLabel.textAlignment = NSTextAlignmentCenter;
    nameLabel.textColor = [UIColor blackColor];
    nameLabel.adjustsFontSizeToFitWidth = YES;
    [bv addSubview:nameLabel];
    
    UIButton *callToButton = [[UIButton alloc] initWithFrame:CGRectMake(bv.frame.size.width-55, nameLabel.frame.origin.y, 50, 40)];
    [callToButton setBackgroundImage:[WDSourceManager WDImageWithName:@"zxf"] forState:UIControlStateNormal];
    [callToButton setTitle:@"安装" forState:UIControlStateNormal];
    [callToButton setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
    callToButton.titleLabel.font = [UIFont systemFontOfSize:15];
    [callToButton addTarget:self action:@selector(callToButton:) forControlEvents:UIControlEventTouchUpInside];
    [bv addSubview:callToButton];
    
    NSArray *cardConfig = [WDBMSModel shareBMSModel].cardConfig;
    NSString *isClose = [NSString stringWithFormat:@"%@",cardConfig[4]];
    
    UIButton *closeButton = [[UIButton alloc] initWithFrame:CGRectMake(0, 0, bv.frame.size.width, bv.frame.size.height-40)];
    closeButton.hidden = ![isClose boolValue];
//    [closeButton setBackgroundColor:[UIColor redColor]];
    [closeButton addTarget:self action:@selector(closeAdView:) forControlEvents:UIControlEventTouchUpInside];
    [bv addSubview:closeButton];
    
    UIButton *closeButton1 = [[UIButton alloc] initWithFrame:CGRectMake(0, bv.frame.size.height-40, bv.frame.size.width-55, nameLabel.frame.size.height)];
    closeButton1.hidden = ![isClose boolValue];
//    [closeButton1 setBackgroundColor:[UIColor yellowColor]];
    [closeButton1 addTarget:self action:@selector(closeAdView:) forControlEvents:UIControlEventTouchUpInside];
    [bv addSubview:closeButton1];
}

- (void)callToButton:(UIButton *)sender
{
    if (self.deepLink.length > 0)
    {
        if (@available(iOS 10.0, *)) {
            [[UIApplication sharedApplication] openURL:[NSURL URLWithString:self.deepLink] options:@{} completionHandler:nil];
            
        }else{
            
            [[UIApplication sharedApplication] openURL:[NSURL URLWithString:self.deepLink]];
            
        }
        
        
    }
}

- (void)cardNativeAd
{
    self.view.backgroundColor = [UIColor clearColor];
    CGFloat safeAreaTop = 0.0;
    CGFloat safeAreaBottom = 0.0;
    if (@available(iOS 11.0, *)) {
        UIViewController *rootViewController = [[[UIApplication sharedApplication].windows objectAtIndex:0] rootViewController];
        safeAreaTop = rootViewController.view.safeAreaInsets.top;
        safeAreaBottom = rootViewController.view.safeAreaInsets.bottom;
    }
    UIView *bv = [[UIView alloc] initWithFrame:CGRectMake(10, self.view.frame.size.height-300-safeAreaBottom-10, 250, 300)];
    bv.backgroundColor = [UIColor whiteColor];
    bv.layer.cornerRadius = 8;
//    [self.view addSubview:bv];
    
    self.adContentView = [[WDNariveAdView alloc] initWithFrame:CGRectMake(10, self.view.frame.size.height-350-safeAreaBottom-10, 250, 350)];
    self.adContentView.backgroundColor = [UIColor whiteColor];;
    [self.view addSubview:self.adContentView];
    
    WDNativeModel *model = [WDNativeModel shareNativeModel];
    
    model.nativeAd.delegate = self;
    
    GADMediaView *mediaView = [[GADMediaView alloc] initWithFrame:CGRectMake(0, self.adContentView.frame.size.height/2-70, self.adContentView.frame.size.width, 140)];
    self.adContentView.mediaView = mediaView;
    [self.adContentView addSubview:self.adContentView.mediaView];
    
    UILabel *headline = [[UILabel alloc] initWithFrame:CGRectMake(0, self.adContentView.frame.size.height-40, self.adContentView.frame.size.width-60, 40)];
    headline.text = model.headline;
    [headline setFont:[UIFont fontWithName:@"Helvetica-Bold" size:20]];
    headline.textAlignment = NSTextAlignmentCenter;
    headline.textColor = [UIColor blackColor];
    headline.adjustsFontSizeToFitWidth = YES;
    self.adContentView.headlineView = headline;
    [self.adContentView addSubview:self.adContentView.headlineView];
    
    UIButton *callToButton = [[UIButton alloc] initWithFrame:CGRectMake(self.adContentView.frame.size.width-55, headline.frame.origin.y, 50, 40)];
    [callToButton setBackgroundImage:[WDSourceManager WDImageWithName:@"zxf"] forState:UIControlStateNormal];
    [callToButton setTitle:model.callToAction forState:UIControlStateNormal];
    [callToButton setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
    callToButton.titleLabel.font = [UIFont systemFontOfSize:15];
    self.adContentView.callToActionView = callToButton;
    [self.adContentView addSubview:self.adContentView.callToActionView];
    
    
    NSArray *cardConfig = [WDBMSModel shareBMSModel].cardConfig;
    NSString *isClose = [NSString stringWithFormat:@"%@",cardConfig[4]];
    
    UIButton *closeButton = [[UIButton alloc] initWithFrame:CGRectMake(0, 0, self.adContentView.frame.size.width, self.adContentView.frame.size.height-40)];
    closeButton.hidden = ![isClose boolValue];
//    [closeButton setBackgroundColor:[UIColor redColor]];
    [closeButton addTarget:self action:@selector(closeAdView:) forControlEvents:UIControlEventTouchUpInside];
    [self.adContentView addSubview:closeButton];
    
    UIButton *closeButton1 = [[UIButton alloc] initWithFrame:CGRectMake(0, self.adContentView.frame.size.height-40, self.adContentView.frame.size.width-55, headline.frame.size.height)];
    closeButton1.hidden = ![isClose boolValue];
//    [closeButton1 setBackgroundColor:[UIColor yellowColor]];
    [closeButton1 addTarget:self action:@selector(closeAdView:) forControlEvents:UIControlEventTouchUpInside];
    [self.adContentView addSubview:closeButton1];
    
    
    
    self.nativeAdView = self.adContentView;
    
//    self.nativeAdView.callToActionView.userInteractionEnabled = NO;

      // Associate the native ad view with the native ad object. This is
      // required to make the ad clickable.
    self.nativeAdView.nativeAd = model.nativeAd;
}

- (void)normalNativeAd
{
    CGFloat width = self.view.frame.size.height>self.view.frame.size.width?self.view.frame.size.width:self.view.frame.size.height;
    CGFloat height = self.view.frame.size.height<self.view.frame.size.width?self.view.frame.size.width:self.view.frame.size.height;
    UIView *bv = [[UIView alloc] initWithFrame:CGRectMake(0, 0, width, height)];
    bv.backgroundColor = [UIColor blackColor];
    [self.view addSubview:bv];
    
    CGFloat safeAreaTop = 0.0;
    if (@available(iOS 11.0, *)) {
        UIViewController *rootViewController = [[[UIApplication sharedApplication].windows objectAtIndex:0] rootViewController];
        safeAreaTop = rootViewController.view.safeAreaInsets.top;
    }
    
    UIView *bv1 = [[UIView alloc] initWithFrame:CGRectMake(0, safeAreaTop, bv.frame.size.width, bv.frame.size.height-50)];
    bv1.backgroundColor = [UIColor colorWithRed:45/255.0 green:53/255.0 blue:61/255.0 alpha:1];
    [self.view addSubview:bv1];
    
    
    
    self.adContentView = [[WDNariveAdView alloc] initWithFrame:CGRectMake(0, safeAreaTop, width, height-safeAreaTop)];
    self.adContentView.backgroundColor = [UIColor colorWithRed:45/255.0 green:53/255.0 blue:61/255.0 alpha:1];
    [self.view addSubview:self.adContentView];
    
    UIButton *closeButton = [[UIButton alloc] initWithFrame:CGRectMake(self.adContentView.frame.size.width-50, 15, 40, 40)];
//    [closeButton setTitle:@"close" forState:UIControlStateNormal];
    [closeButton setBackgroundImage:[WDSourceManager WDImageWithName:@"close"] forState:UIControlStateNormal];
    [closeButton setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    [closeButton addTarget:self action:@selector(closeAdView:) forControlEvents:UIControlEventTouchUpInside];
    [self.adContentView addSubview:closeButton];
    
    WDNativeModel *model = [WDNativeModel shareNativeModel];
    
    model.nativeAd.delegate = self;
    
//    UIImageView *contentImageView = [[UIImageView alloc] initWithFrame:CGRectMake(10, closeButton.frame.origin.y+closeButton.frame.size.height+10, self.adContentView.frame.size.width-20, 200)];
//    contentImageView.image = model.mediaContent.mainImage;
//
//    if (model.mediaContent.aspectRatio > 0)
//    {
////        [self.adContentView addSubview:contentImageView];
//    }
    
    GADMediaView *mediaView = [[GADMediaView alloc] initWithFrame:CGRectMake(10, closeButton.frame.origin.y+closeButton.frame.size.height+10, self.adContentView.frame.size.width-20, 200)];
    self.adContentView.mediaView = mediaView;
    [self.adContentView addSubview:self.adContentView.mediaView];
    
    if (model.mediaContent.hasVideoContent)
    {
        model.mediaContent.videoController.delegate = self;
        WDLog(@"有视频");
    }
    else
    {
        WDLog(@"无视频");
    }
    
    
    UIImageView *iconImageView = [[UIImageView alloc] initWithFrame:CGRectMake(self.adContentView.center.x-30, self.adContentView.center.y-30, 60, 60)];
//    iconImageView.center = self.adContentView.center;
    iconImageView.image = model.iconImage;
    iconImageView.layer.cornerRadius = 8.0;
    iconImageView.clipsToBounds = YES;
    self.adContentView.iconView = iconImageView;
    [self.adContentView addSubview:self.adContentView.iconView];
    
    UILabel *headline = [[UILabel alloc] initWithFrame:CGRectMake(0, iconImageView.frame.origin.y+iconImageView.frame.size.height+15, self.adContentView.frame.size.width, 40)];
    headline.text = model.headline;
    [headline setFont:[UIFont fontWithName:@"Helvetica-Bold" size:20]];
    headline.textAlignment = NSTextAlignmentCenter;
    headline.textColor = [UIColor whiteColor];
    self.adContentView.headlineView = headline;
    [self.adContentView addSubview:self.adContentView.headlineView];
    
    UIImageView *starImageView = [[UIImageView alloc] initWithFrame:CGRectMake(self.adContentView.center.x-50, headline.frame.origin.y+headline.frame.size.height+15, 100, 20)];
    starImageView.image = [WDSourceManager WDImageWithName:model.starImageName];
    self.adContentView.starRatingView = starImageView;
    [self.adContentView addSubview:self.adContentView.starRatingView];
    
    UILabel *priceLabel = [[UILabel alloc] initWithFrame:CGRectMake(0, starImageView.frame.origin.y+starImageView.frame.size.height+10, self.adContentView.frame.size.width/2-20, 30)];
    priceLabel.textColor = [UIColor whiteColor];
    priceLabel.textAlignment = NSTextAlignmentRight;
    priceLabel.text = [NSString stringWithFormat:@"%@",model.price];
    priceLabel.font = [UIFont systemFontOfSize:13];
    self.adContentView.priceView = priceLabel;
    if (!model.price)
    {
        self.adContentView.priceView.hidden = YES;
    }
    [self.adContentView addSubview:self.adContentView.priceView];
    
    UILabel *storeLabel = [[UILabel alloc] initWithFrame:CGRectMake(self.adContentView.frame.size.width/2, priceLabel.frame.origin.y, priceLabel.frame.size.width, priceLabel.frame.size.height)];
    storeLabel.textColor = [UIColor whiteColor];
    storeLabel.textAlignment = NSTextAlignmentLeft;
    storeLabel.text = [NSString stringWithFormat:@"%@",model.store];
    storeLabel.font = [UIFont systemFontOfSize:13];
    self.adContentView.storeView = storeLabel;
    if (!model.store) {
        self.adContentView.storeView.hidden = YES;
    }
    [self.adContentView addSubview:self.adContentView.storeView];

    
    UILabel *bodyLabel = [[UILabel alloc] initWithFrame:CGRectMake(30, priceLabel.frame.origin.y+priceLabel.frame.size.height+15, self.adContentView.frame.size.width-60, 40)];
    bodyLabel.numberOfLines = 2;
    bodyLabel.textColor = [UIColor lightGrayColor];
    bodyLabel.font = [UIFont systemFontOfSize:15];
    bodyLabel.textAlignment = NSTextAlignmentCenter;
    bodyLabel.text = model.body;
    self.adContentView.bodyView = bodyLabel;
    [self.adContentView addSubview:self.adContentView.bodyView];
    
    UIButton *callToButton = [[UIButton alloc] initWithFrame:CGRectMake(20, bodyLabel.frame.size.height+bodyLabel.frame.origin.y+20, self.adContentView.frame.size.width-40, 40)];
    [callToButton setBackgroundColor:[UIColor redColor]];
    [callToButton setTitle:model.callToAction forState:UIControlStateNormal];
    [callToButton setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    self.adContentView.callToActionView = callToButton;
    [self.adContentView addSubview:self.adContentView.callToActionView];
    
    self.nativeAdView = self.adContentView;
    
//    self.nativeAdView.callToActionView.userInteractionEnabled = NO;

      // Associate the native ad view with the native ad object. This is
      // required to make the ad clickable.
    self.nativeAdView.nativeAd = model.nativeAd;
}

- (void)closeAdView:(UIButton *)sender
{
    [[NSUserDefaults standardUserDefaults] setObject:@"0" forKey:@"WDOrientation"];
    dispatch_async(dispatch_get_main_queue(), ^{
        [[self navigationController] dismissViewControllerAnimated:NO completion:^{
            if (self.delegate && [self.delegate respondsToSelector:@selector(dismiss)])
            {
                [self.delegate dismiss];
            }
        }];
    });
}

- (void)callToActionView
{
    
}

#pragma mark GADVideoControllerDelegate implementation
- (void)videoControllerDidEndVideoPlayback:(GADVideoController *)videoController {
  
    WDLog(@"videoControllerDidEndVideoPlayback");
}

#pragma mark GADUnifiedNativeAdDelegate
- (void)nativeAdDidRecordClick:(GADNativeAd *)nativeAd {
    [[WDAdStatusManager shareStatusManager] adClickWithEventName:NATIVE_EVENT_NAME];
  WDLog(@"===========%s", __PRETTY_FUNCTION__);
}

- (void)nativeAdDidRecordImpression:(GADNativeAd *)nativeAd {
  WDLog(@"%s", __PRETTY_FUNCTION__);
}

- (void)nativeAdWillPresentScreen:(GADNativeAd *)nativeAd {
  WDLog(@"%s", __PRETTY_FUNCTION__);
}

- (void)nativeAdWillDismissScreen:(GADNativeAd *)nativeAd {
  WDLog(@"%s", __PRETTY_FUNCTION__);
}

- (void)nativeAdDidDismissScreen:(GADNativeAd *)nativeAd {
  WDLog(@"%s", __PRETTY_FUNCTION__);
}

- (void)nativeAdWillLeaveApplication:(GADNativeAd *)nativeAd {
  WDLog(@"%s", __PRETTY_FUNCTION__);
}



/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
